package javaExample;

/**
 * @author admin
 *         把字符串中的每个空格替换成%20.如We are happy,则输出We%20are%20happy
 */
public class ReplaceSpace {
    public void repalce(char[] oldchar, char[] replacement) {
        int sumOfSpace = 0;
        for (int i = 0; i < oldchar.length; i++) {
            if (oldchar[i] == ' ')
                sumOfSpace++;
        }
        if (sumOfSpace == 0) {
            return;
        }
        char[] newchar = new char[oldchar.length + (replacement.length - 1)
                * sumOfSpace];
        // 指向被替换字符串的最后一个元素
        int pOld = oldchar.length - 1;
        // 指向替换字符串的最后一个元素
        int pNew = newchar.length - 1;
        while (pNew >= 0) {
            if (oldchar[pOld] == ' ') {
                pOld--;
                for (int j = replacement.length - 1; j >= 0; j--) {
                    newchar[pNew--] = replacement[j];
                }
            } else {
                newchar[pNew--] = oldchar[pOld--];
            }
        }
        for (char c : newchar) {
            System.out.print(c);
        }
    }

    /**
     * 替换字符串中的空格，正序
     * @param oldChar
     * @param replaceChar
     * @return
     */
    public char[] ReplaceSpaceAnother(char[] oldChar, char[] replaceChar) {
        int replaceNum = 0;
        for (int i = 0; i < oldChar.length; i++) {
            if (oldChar[i] == ' ') {
                replaceNum++;
            }
        }
        if (replaceNum == 0) {
            return null;
        }
        int oldLength = oldChar.length;
        int newLenght = oldLength+(replaceChar.length-1)*replaceNum;
        char[] newChar = new char[newLenght];
        int j =0;//旧数组
        int n =0;// 新数组
        while(j<oldLength){
            if(oldChar[j]==' '){
                for (int m=0;m<replaceChar.length;m++){
                    newChar[n++] = replaceChar[m];
                    System.out.println("n=="+n);
                    System.out.println("m=="+m);
                }
                j++;
            }else{
                newChar[n++]=oldChar[j++];
            }
        }
        for(char c :newChar){
            System.out.print(c);
        }
        return null;
    }

    public static void main(String[] args) {
        char[] ch = "We are happy".toCharArray();
        ReplaceSpace rs = new ReplaceSpace();
       // rs.repalce(ch, "%20".toCharArray());
        rs.ReplaceSpaceAnother(ch,"%20".toCharArray());
    }
}
